package com.av.bcacc.javaapi.thread.reentrantlock;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockRunnable implements Runnable {

    private int ticketCount = 100;
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (ticketCount <= 0) {
                    break;
                }
                Thread.sleep(100);
                ticketCount--;
                System.out.println(Thread.currentThread().getName() + "在售票，还剩" + ticketCount + "张票");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();//解锁一般放到finally里面，防止异常导致死锁
            }
        }
    }
}
